const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const getUserResult = await db.collection("user").where({
    openId: wxContext.OPENID
  }).get()
  console.log("getUserResult===" + JSON.stringify(getUserResult))
  if (getUserResult.errMsg == "collection.get:ok" && getUserResult.data.length > 0) {
    if (getUserResult.data[0].openId) {
      return {
        code: 0,
        userInfo: getUserResult.data[0]
      }
    } else {
      return {
        code: -1,
      }
    }
  } else {
    console.log("getUserResult" + JSON.stringify(getUserResult))
    const addUserResult = await db.collection("user").add({
      data: {
        nickName: event.nickName,
        openId: wxContext.OPENID,
        avatarUrl: event.avatarUrl,
        gender: event.gender,
        score:0
      }
    })
    console.log("addUserResult" + JSON.stringify(addUserResult))
    if (addUserResult.errMsg == "collection.add:ok") {
      return {
        code: 0,
        userInfo: {
          nickName: event.nickName,
          openId: wxContext.OPENID,
          avatarUrl: event.avatarUrl,
          gender: event.gender,
          score:0
        }
      }
    } else {
      return {
        code: -1,
        msg: addUserResult.errMsg
      }
    }
  }
}